package soft.net.model;

import soft.common.StringUtil;

/**
 * 客户端监听类
 * 
 * @author fanpei
 *
 */
public abstract class NetEventListenerBase {
	public CusNetSource channel;// 连接链路
	protected boolean contimeoutFlag;// 是否超时
	protected boolean recvtimeoutFlag;// 是否超时
	private Object lock;// 连接对象对象

	/**
	 * 是否连接超时
	 * 
	 * @return
	 */
	public boolean isConTimeout() {
		return contimeoutFlag;
	}

	public CusNetSource getNetSource() {
		return channel;
	}

	public void setNetSource(CusNetSource ch) {
		this.channel = ch;
	}

	public NetEventListenerBase() {
		this.lock = new Object();
	}

	/**
	 * 连接等待
	 * 
	 * @throws InterruptedException
	 */
	public void connectWait(int timeout) throws InterruptedException {
		synchronized (lock) {
			try {
				contimeoutFlag = true;
				while (true) {
					lock.wait(timeout);//// 延时
					break;
				}
			} catch (InterruptedException e) {
				throw new InterruptedException(StringUtil.getMsgStr("连接{}服务反馈结果时，意外中断\"", channel.getRIpPort()));
			}
		}
	}

	/**
	 * 连接等待完成
	 */
	public void connectNotify() {
		synchronized (lock) {
			contimeoutFlag = false;
			lock.notifyAll();
		}
	}

	/**
	 * 是否接受数据超时
	 * 
	 * @return
	 */
	public boolean isRecvTimeout() {
		return recvtimeoutFlag;
	}

	/**
	 * 数据接收等待
	 * 
	 * @throws CusException
	 */
	public void reciveWait(int timeout) throws InterruptedException {
		synchronized (lock) {
			try {
				recvtimeoutFlag = true;
				while (true) {
					lock.wait(timeout);// 延时 ConfigClient.SHORTCONECT_REVDATA_WAITTIMEOUT
					break;
				}
			} catch (InterruptedException e) {
				throw new InterruptedException(StringUtil.getMsgStr("\"等待{}服务反馈结果时，意外中断\"", channel.getRIpPort()));
			}
		}
	}

	/**
	 * 数据接收等待完成
	 */
	public void reciveNotify() {
		synchronized (lock) {
			recvtimeoutFlag = false;
			lock.notifyAll();
		}
	}

	public void release() {
		if (channel != null)
			channel.close();
	}
}
